package com.example.controller;

import com.example.bo.RedisUserInfo;
import com.example.bo.UserSaveDetails;
import com.example.dto.CmsLogin;
import com.example.dto.CmsUserRegisterDto;
import com.example.service.ICmsUserService;
import com.example.utils.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author zhengyue
 * @since 2020-03-13
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户 用户管理")
public class CmsUserController {
    @Autowired
    private ICmsUserService cmsUserService;
    @Autowired
    private UserSaveDetails saveDetails;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/hello")
    @PreAuthorize("hasAnyAuthority('user:hello')")
    public CommonResult hello() {

        return CommonResult.success(saveDetails.getCmsUser().getNumber());
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody CmsLogin cmsLogin) {
        RedisUserInfo info = cmsUserService.login(cmsLogin);
        if(info.getToken() == null) {
            return CommonResult.validateFailed("账号密码错误");
        }
        return CommonResult.success(info);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public CommonResult register(@RequestBody @Validated CmsUserRegisterDto registerDto) {
        Boolean register = cmsUserService.register(registerDto);
        if(register) {
            return CommonResult.success("注册成功");
        }
        return CommonResult.failed("注册失败，该账户已存在");
    }

}
